function [ parsed_feature_set ] = parse_feature_set( feature_set, header )
%PARSE_FEATURE_SET Summary of this function goes here
%   Detailed explanation goes here

if ~iscell(feature_set)
    fcell{1} = feature_set;
else
    fcell = feature_set;
end
fcell = unique(fcell);

parsed_feature_set = {};
for i=1:length(fcell)
    fname = fcell{i};
    if isempty(fname)
        continue;
    end
    fstruct = feature_name_parser(fname);
    input_ch = get_input_channels(fstruct, header);
    fstruct.input_ch = input_ch;
    parsed_feature_set{end+1} = fstruct;
end

end

function [ fstruct ] = feature_name_parser( fname )

[f, rem] = strtok(fname, ':');
if isempty(rem)
    error(['Bad feature name: ' fname]);
end

[fid, fch] = strtok(f, '/');
if length(fch)<=1
    fch = 0;
else
    fch = str2num(fch(2:end));
end

fstruct.feature_id = fid;
fstruct.feature_channel = fch;
fstruct.inputs = {};

rem = rem(2:end);
while ~isempty(rem)
    [c, rem] = strtok(rem, ',');
    [cid, cch] = strtok(c, '/');
    if length(cch)<=1
        cch = 0;
    else
        cch = str2num(cch(2:end));
    end
    tmp_input.sensor_id = cid;
    tmp_input.sensor_channel = cch;
    fstruct.inputs{end+1} = tmp_input;
    if isempty(rem)
        rem = rem(2:end); 
    end
end

end

function [ input_ch ] = get_input_channels( fstruct, header )

c = 2;
for i=1:length(header)
    header{i}.first_channel = c;
    if isfield(header{i}, 'channels')
        c = c + header{i}.channels;
    else
        c = c + 3;
    end
end

input_ch = zeros(1, length(fstruct.inputs));
for i=1:length(fstruct.inputs)
    tmp_i = fstruct.inputs{i};
    sid = str2num(tmp_i.sensor_id);
    if isempty(sid)
        for j=1:length(header)
            if strcmp(header{j}.sensorName, tmp_i.sensor_id)
                sid = j; break;
            end
        end
    end
    if isempty(sid)
        error(['Sensor ' tmp_i.sensor_id ' not found.']);
    end
    input_ch(i) = header{sid}.first_channel + tmp_i.sensor_channel -1;
end

end
